package cn.nami.web.frontpage.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.nami.web.frontpage.entity.Visitor;
import cn.nami.web.frontpage.jdo.VisitorJdo;
import cn.nami.web.util.WebUtil;

@SuppressWarnings("serial")
public class FrontServlet extends HttpServlet
{
	private static final Logger logger = Logger.getLogger(FrontServlet.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		saveVisitors(request);
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request, response);
	}
	
	private void saveVisitors(HttpServletRequest request)
	{
		try
		{
			// 1. create a visitor
			String clientIp = WebUtil.getIpAddr(request);
			String clientAddress = WebUtil.getAdress(clientIp);
			Visitor visitor = new Visitor(clientIp, clientAddress, new Date());
			
			// 2. save to db
			VisitorJdo.save(visitor);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.severe("save visitor error..." + e.getMessage());
		}
	}
}
